<template>
  <div class="update">
    <div class="body">
      <div class="body-update">
        <h2>编辑资料</h2>
        <!-- <img :src="mes.avatar" alt="" class="be-avatar"> -->
        <el-form :model="mes" :rules="rules" ref="mes" label-width="80px" class="demo-ruleForm">
          <el-form-item label="头像："  >
            <!-- <input type="file" @change="uploadImg($event)"> -->
            <!-- <input type="file" @change="changeflie($event)"> -->
            <img :src="mes.avatar" alt="" class="avatar be-avatar" @click.stop="uploadHeadImg">
            <input type="file" accept="image/*" @change="handleFile" class="hiddenInput" />
            <!-- <el-upload
              class="avatar-uploader"
              action="https://www.mocky.io/v2/5185415ba171ea3a00704eed/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="mes.avatar" :src="mes.avatar" class="avatar be-avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload> -->

          </el-form-item>
          <el-form-item label="昵称：" prop="nickname" >
            <el-input placeholder="请输入昵称" v-model="mes.nickname" clearable maxlength="10"></el-input>
          </el-form-item>
          <el-form-item label="账号：" prop="account" >
            <el-input placeholder="请输入账号" v-model="mes.account" disabled clearable></el-input>
          </el-form-item>
          <el-form-item label="简介：" prop="Introduction" >
            <el-input placeholder="介绍一下自己吧，尽量不要超过20个字哦" v-model="mes.Introduction" clearable maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="性别：" prop="sex">
            <el-select v-model="mes.sex" placeholder="性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
              <el-option label="不显示" value="保密"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生日：" prop="birthday">
            <el-date-picker v-model="mes.birthday" align="right" type="date" placeholder="选择日期"  :picker-options="pickerOptions"></el-date-picker>
          </el-form-item>
          <el-form-item label="地区：" prop="district">
            <el-input placeholder="请输入地区" v-model="mes.district" clearable></el-input>
          </el-form-item>
          <el-form-item label="学校：" prop="school">
            <el-input placeholder="请输入学校" v-model="mes.school" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('mes')">修改</el-button>
            <el-button @click="resetForm('mes')">重置</el-button>
          </el-form-item>
        </el-form>

      </div>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return {
      mes:{},
      mes_avatar:"",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }],
        imageUrl: ''
      },
      date: '',
      // imageUrl: '',
      rules:{
        nickname:[
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        account:[
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        Introduction:[
          { required: true, message: '请输入简介', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  mounted(){
    this.getMessage();
  },
  methods:{
    // 获取用户资料
    async getMessage(){
      console.log("这是编辑资料获取信息");
      var variate = this.$route.query.id;
      const {data:res} = await this.$http.post("selPersonal",{variate});
      if(res.status != 200){
        his.$message.error('获取数据失败！');
      }else{
        console.log(res);
        this.mes = res.message[0];
         this.mes.birthday = this.mes.birthday.split("T")[0];
        //  this.mes.avatar = 'http://127.0.0.1:3000/images/a/'+this.mes.avatar
      }
    },
    uploadHeadImg: function() {
      //打开图片上传,获取文档中class为hiddenInput的元素
      this.$el.querySelector(".hiddenInput").click();
    },
    //将头像显示
    async handleFile(e) {
      //调用他的各种属性 区别：ie下支持e.srcElement,ff支持e.target;
      let $target = e.target || e.srcElement;
      //手机上可以选择多张图片，下面这行代码表示取第一张图
      let file = $target.files[0];
      console.log($target.files[0].name);
      this.mes_avatar = "http://127.0.0.1:3000/images/a/"+$target.files[0].name;
      //FileReader对象允许WEB应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用File或Blob对象指定要读取的文件或数据
      var reader = new FileReader();
      //onload事件会在页面或图像加载完成后立即发生
      reader.onload = data => {
        let res = data.target || data.srcElement;
        this.mes.avatar = res.result;
        // var avatar = res.result;
        // console.log(res.result);
        // console.log(this.userInfo.avatar);
        // reader.readAsDataURL(file);
      };
    // console.log(this.userInfo.avatar);
      // console.log(avatar);
      // const {data:res} = await this.$http.post("updateAvatar",{avatar});
      //FileReader的readAsDataURL方法可以将读取到的文件编码成Data Url
      reader.readAsDataURL(file);

    },
    // 点击修改按钮
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.updateMes()

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 更新资料
    async updateMes(){
      console.log("这里是编辑资料");
      console.log(this.mes);
      // replace(/+/g,"%2B")
      // let img = this.mes.avatar.replace(/^data:image\/\w+;base64,/,"");
      //  imageData.replace(/+/g,"%2B")；
      // this.mes.avatar = img.replace(/\+/g,"%2B");
      this.mes.avatar = this.mes_avatar;
      var user = JSON.stringify(this.mes);
      console.log(this.mes);
      const updateUser = {};
      updateUser.user_id = this.mes.user_id;
      updateUser.account = this.mes.account;
      updateUser.password = this.mes.password;
      updateUser.nickname = this.mes.nickname;
      // updateUser.avatar = this.mes.avatar;
      updateUser.avatar = this.mes_avatar;
      updateUser.userType = this.mes.userType;
      console.log(updateUser);
       this.$store.commit("updateUser",updateUser);
       this.$store.commit("updateShow",true);
      const {data:res} = await this.$http.post('updateMes',{user});
      console.log(res);
      var id = this.mes.user_id
      this.$message({
          message: '修改成功！',
          type: 'success'
        });
      this.$router.push({path:"/personalTabbar",query:{id}});
    },
    // 重置用户信息
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 以下为用户头像上传
    // handleAvatarSuccess(res, file) {
    //   this.mes.avatar = URL.createObjectURL(file.raw);
    //   console.log(this.mes.avatar);
    // },
    // beforeAvatarUpload(file) {
    //   const isJPG = file.type === 'image/jpeg';
    //   const isLt2M = file.size / 1024 / 1024 < 2;

    //   if (!isJPG) {
    //     this.$message.error('上传头像图片只能是 JPG 格式!');
    //   }
    //   if (!isLt2M) {
    //     this.$message.error('上传头像图片大小不能超过 2MB!');
    //   }
    //   return isJPG && isLt2M;
    // },
    uploadImg(e){
      let file = e.target.files[0];
      // console.log(e.target.files);
      console.log(file);
      let fileSize = file.size;
      let fileName = file.name;
      if(fileSize>2101440){
        // 图片大于2MB

      }
      let reader = new FileReader();
      console.log(reader);
      reader.readAsDataURL(file);
      reader.onload = e => {
        // 读取到的图片 base64 数据编码将此编码字符串传给后台即可
        let imgCode = e.target.result;
        this.mes.avatar = imgCode;
        console.log(this.mes.avatar);
        this.insert(this.mes.avatar)
      }
    },
    async insert(imgUrls){
      let imgUrl = "www";
      const {data:res} = await this.$http.post("insertCeshi",{imgUrl});
      console.log(res);
    },
    // changeflie(event){
    //     var files = event.target.files[0]        //获取文件
    //     let formData = new FormData();
    //     formData.append('file', files);         //file  是你接口参数名
    //     api.upload(formData).then(res=>{     	//请求接口
    //     	console.log(res)
    //     })
    // },
        // 上传头像前校验
    // beforeUpload(file) {
    //   const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
    //   if (!isJpgOrPng) {
    //     this.$message.error('只能上传jpg/png格式的头像!')
    //   }
    //   const isLt2M = file.size / 1024 / 1024 < 2
    //   if (!isLt2M) {
    //     this.$message.error('图片不得大于2MB!')
    //   }
    //   return isJpgOrPng && isLt2M
    // },
    // // 上传头像
    uploadImage(file) {
      this.avatarLoading = true
      const formData = new FormData()
      formData.append('file', file.file)
      api.upload(formData).then(res => {
        if (res) {
          this.imageUrl = res.data.data.link
          this.saveAvatar() // 保存新头像
          this.avatarLoading = false
        }
      }, err => {
        this.avatarLoading = false
      })
    },
  }
}
</script>
<style scoped>
@import url('./css/person.css');

</style>
